package com.woniuxy.shiro_ini;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @Author 罗蔚
 * @Date 2022/4/13 20:01
 * @Description 自定义域 重新认证和授权的具体方法
 */
public class CustomRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //登录认证成功后，从SimpleAuthenticationInfo中取出的校长的信息
        String primaryPrincipal = principals.getPrimaryPrincipal()+"";
        //模拟去数据库中，查出该用户的所有角色和权限，并封装到SimpleAuthorizationInfo中！
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //添加角色：角色和权限是从数据库中查出, 在这里模拟查出的数据
        simpleAuthorizationInfo.addRole("boss");
        simpleAuthorizationInfo.addRole("teacher");
        //添加权限：
        simpleAuthorizationInfo.addStringPermission("eat::person");
        simpleAuthorizationInfo.addStringPermission("yue:ma");
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        //去数据库中查出用户名和密码
        String findName = "luowei";
        String findPassword = "123456";
        if(findName.equals(username)){
            //CustomRealm是自定义的域
            return new SimpleAuthenticationInfo(username,findPassword,"CustomRealm");
        }

        return null;
    }
}
